import json
import re
from django.http import JsonResponse, HttpResponse
from django.utils.decorators import method_decorator
from django.views import View
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from django.views.decorators.csrf import ensure_csrf_cookie


class ImageCodeView(View):

    @method_decorator(ensure_csrf_cookie)
    def get(self, request):
        """获取图片验证码"""

        # 获取数据
        cur = request.GET.get('cur')
        pre = request.GET.get('pre')

        # 校验数据
        if not cur:
            return JsonResponse({
                'errno': 9999,
                'errmsg': '参数不全'
            })

        # 生成图片验证码
        text, image = captcha.generate_captcha()

        # 写入redis
        redis_client = get_redis_connection('verify')
        if pre:
            redis_client.delete(pre)

        redis_client.setex(cur, 300, text)

        # 返回图片
        return HttpResponse(image, content_type='image/jpeg')


class SmsCodeView(View):
    def post(self, request):
        """获取短信验证码"""

        # 获取数据
        mobile = json.loads(request.body).get('mobile')
        text = json.loads(request.body).get('text')
        uuid = json.loads(request.body).get('id')

        # 校验数据
        if not all([mobile, text, uuid]):
            return JsonResponse({
                'errno': '9999',
                'errmsg': '参数不全'
            })

        redis_client = get_redis_connection('verify')
        img_text = redis_client.get(uuid)
        if img_text:
            img_text = img_text.decode()

        if text.upper() != img_text.upper():
            return JsonResponse({
                'errno': '9999',
                'errmsg': '验证码错误'
            })
        redis_client.delete(uuid)

        if not re.match(r'1[34578]\d{9}', mobile):
            return JsonResponse({
                'errno': '9999',
                'errmsg': '手机号格式错误'
            })

        # 发送短信验证码
        from random import randint
        sms_code = '%06d' % randint(0, 999999)
        redis_client.setex('sms_code_%s' % mobile, 300, sms_code)
        print('短信验证码: {}'.format(sms_code))

        # from libs.yuntongxun.sms import CCP
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, 5], 1)

        # from main import send_sms_code
        # send_sms_code.delay(mobile, sms_code)

        return JsonResponse({
            'errno': '0',
            'errmsg': '发送成功'
        })
